package com.toune.dealexception.dealException

import android.app.Application
import android.content.Context
import android.os.Looper
import android.util.Log

object DealExceptionTool {
    private lateinit var cxt: Application
    private lateinit var context: Context

    /**
     * 初始化
     * @param cxt Application
     * @return DLTool
     */
    fun init(cxt: Application): DealExceptionTool {
        this.cxt = cxt
        context = cxt.applicationContext
        if (token.isBlank()) {
            token = "com.toune.dealException"
        }
        return this
    }

    fun init(cxt: Application, isOpen: Boolean): DealExceptionTool {
        init(cxt)
        openCrash(isOpen)
        return this
    }

    val SP_TOKEN = "SP_TOKEN";
    var token = ""

    fun init(cxt: Application, isOpen: Boolean, token: String): DealExceptionTool {
        this.token = token
        init(cxt, isOpen)
        return this
    }

    /**
     * 打开错误信息抓取，防止软件崩溃
     */
    fun openCrash(isOpen: Boolean) {
        if (isOpen) {
            Cockroach.install(cxt, object : ExceptionHandler() {
                override fun onUncaughtExceptionHappened(thread: Thread?, throwable: Throwable?) {
                    Log.e(
                        "AndroidRuntime",
                        "--->onUncaughtExceptionHappened:\$thread<---",
                        throwable
                    )
                }

                override fun onBandageExceptionHappened(throwable: Throwable) {
                    throwable.printStackTrace() //打印警告级别log，该throwable可能是最开始的bug导致的，无需关心
                }

                override fun onEnterSafeMode() {}
                override fun onMayBeBlackScreen(e: Throwable?) {
                    val thread = Looper.getMainLooper().thread
                    Log.e(
                        "AndroidRuntime",
                        "--->onUncaughtExceptionHappened:\$thread<---",
                        e
                    )
                }
            })
        }
    }
}